package com.gistone.commis.api.restController;

import com.gistone.commis.constant.Status;
import com.gistone.commis.database.GetBySqlMapper;
import com.gistone.commis.dto.EditorResult;
import com.gistone.commis.dto.FieldError;
import com.gistone.commis.dto.Result;
import com.gistone.commis.entity.*;
import com.gistone.commis.mapper.AttendanceMapper;
import com.gistone.commis.mapper.AttendanceNotifyMapper;
import com.gistone.commis.mapper.PersonMapper;
import com.gistone.commis.mapper.UserMapper;
import com.gistone.commis.query.QueryAttendance;
import com.gistone.commis.query.QueryHouse;
import com.gistone.commis.util.DataTablePageUtil;
import com.gistone.commis.util.ZipUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.io.File;
import java.util.*;

/**
 * Created by wangfan on 2017/5/5.
 */
@RestController("apiAttendanceController")
@RequestMapping("api/attendance")
public class AttendanceController {

    private static final Logger logger = LoggerFactory.getLogger(AttendanceController.class);

    @Value("${app.uploadPath}")
    private String path;
    @Autowired
    private AttendanceMapper attendanceMapper;
    @Autowired
    private AttendanceNotifyMapper attendanceNotifyMapper;

    @Autowired
    private GetBySqlMapper getBySqlMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PersonMapper personMapper;

    @Transactional
    @RequestMapping(method = RequestMethod.GET, value = "/pageNotifyDatatables")
    public DataTablePageUtil<Map> pageNotifyDatatables(HttpServletRequest request, @RequestParam  Integer flag ) {
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        Calendar now = Calendar.getInstance();
        int nowYear =now.get(Calendar.YEAR);
        int nowMonth =now.get(Calendar.MONTH) + 1;
        String sql = "select tb_attendance_notify.*,tb_community.community_name  from tb_attendance_notify,tb_community where tb_attendance_notify.community_id =tb_community.community_id  and year  =" +nowYear+" and month =" +nowMonth+" and flag =" +flag;

        DataTablePageUtil<Map> dataTable = new DataTablePageUtil<>(request);
        PageHelper.startPage(dataTable.getPage_num(), 10);
        List<Map> list =		this.getBySqlMapper.findRecords(sql);
        PageInfo<Map> pageInfo =new PageInfo<>(list);
        System.out.println(list.size());
        dataTable.setDraw(dataTable.getDraw());
        dataTable.setData(pageInfo.getList());
        dataTable.setRecordsTotal((int)pageInfo.getTotal());
        dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
        //返回数据到页面

        return dataTable;

    }




    @RequestMapping("/alterFlag")
    public Result alterFlag(@RequestParam Integer flag,@RequestParam Integer communityId, HttpServletResponse response) throws Exception {
        Date d= new Date();
        Calendar now = Calendar.getInstance();
        int nowYear =now.get(Calendar.YEAR);
        int nowMonth =now.get(Calendar.MONTH) + 1;


           if(attendanceNotifyMapper.selectByCommunityAndYearAndMonth(communityId,nowYear,nowMonth).size()>0){

               AttendanceNotify attendanceNotify =attendanceNotifyMapper.selectByCommunityAndYearAndMonth(communityId,nowYear,nowMonth).get(0);

               attendanceNotify.setFlag(flag);
               attendanceNotifyMapper.updateByPrimaryKeySelective(attendanceNotify);
               if(flag==1) {//确定数据正确
                   return new Result(Status.SUCCESS, "确定成功", "");
               }else  if(flag==3){//返回修改
                   return  new Result(Status.SUCCESS,"成功返回修改",null);
               }else{
                   return  new Result(Status.SUCCESS,"成功",null);
               }

           }else{
               return  new Result(Status.ERROR,"所选社区还没有上传对应数据",null);
           }







    }

    @RequestMapping("/isExist")
    public Result isExist(@RequestParam Integer year,@RequestParam Integer month, HttpServletResponse response) throws Exception {
        List<File> fileList = new ArrayList<>();


        String downloadPath =path+"/考勤/"+year+"/"+month;
        File file =new File(downloadPath);
        if(file.isDirectory()){
            File[] files =file.listFiles();
            for (File file1 : files) {
                fileList.add(file1);
            }
        }
        if(fileList.size()>0){
            return new Result("exist");
        }else{
            return  new Result(Status.ERROR,"没有数据文件",null);
        }


    }

    @RequestMapping("/btDownload")
    public void btDownload(@RequestParam Integer year,@RequestParam Integer month, HttpServletResponse response) throws Exception {
        List<File> fileList = new ArrayList<>();

        String tmpFileName = "考勤"+"-"+year+"-"+month+".zip";

            String downloadPath =path+"/考勤/"+year+"/"+month;
            File file =new File(downloadPath);
            if(file.isDirectory()){
                File[] files =file.listFiles();
                for (File file1 : files) {
                    fileList.add(file1);
                }
            }

            ZipUtil.downLoadFiles(fileList,tmpFileName,response);

    }


    @Transactional
    @RequestMapping(method = RequestMethod.GET, value = "/pageDatatables")
    public DataTablePageUtil<Attendance> pageDatatables(HttpServletRequest request, QueryAttendance attendance) {
//		HttpSession httpSession = request.getSession();
//		User user = (User) httpSession.getAttribute("userInfo");
//		logger.info("用户信息：" + user.toString());
//		int community_id = user.getCommunity().getCommunityId();
//		person.setCommunityId(community_id);



        DataTablePageUtil<Attendance> dataTable = new DataTablePageUtil<>(request);

        PageHelper.startPage(dataTable.getPage_num(), 10);
        List<Attendance> list = attendanceMapper.selectSelective(attendance);

        PageInfo<Attendance> pageInfo = new PageInfo<>(list);
        dataTable.setDraw(dataTable.getDraw());
        dataTable.setData(pageInfo.getList());
//        dataTable.setOptions(os);
        dataTable.setRecordsTotal((int) pageInfo.getTotal());
        dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
        //返回数据到页面

        return dataTable;

    }




    /**
     * 获取所有社区
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/all")
    public List<Attendance> loadAll() {
        return attendanceMapper.findAttendances();
    }


    /**
     * 批量考勤信息， id以,号分割
     *
     * @param attendanceIdStr
     * @param request
     * @return
     */

    @Transactional
    @RequestMapping(method = RequestMethod.PUT, value = "/edit")
    public Object edit(@RequestParam("id") String attendanceIdStr, HttpServletRequest request, HttpServletResponse response) {

        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        String[] arr = attendanceIdStr.split(",");
        EditorResult<Attendance> attendanceEditorResult = new EditorResult<>();
        List<Attendance> data =new ArrayList<>();

        for (int i = 0; i < arr.length; i++) {
            int attendanceId = Integer.valueOf(arr[i]);
            Attendance attendance = new Attendance();
            attendance.setAttId(attendanceId);
            List<FieldError> fieldErrorList = new ArrayList<>();
            getAttendance(request, "data[" + attendanceId + "][", attendance,fieldErrorList);
            if(fieldErrorList.size()>0){
                logger.error("字段错误");
                attendanceEditorResult.setFieldErrors(fieldErrorList);
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return attendanceEditorResult;
            }
            if (attendanceMapper.updateByPrimaryKeySelective(attendance) > 0) {
                Attendance h = attendanceMapper.selectByPrimaryKey(attendanceId);
                data.add(h);








            }else{
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }


        }
        attendanceEditorResult.setData(data);
        return attendanceEditorResult;


    }

    /**
     * 添加当月考勤数据
     * @param request
     * @param ids
     * @param leaveAffairs
     * @param leaveSicks
     * @param leaveYears
     * @param leaveMaternitys
     * @param leaveMarriages
     * @param leaveFunerals
     * @param response
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = "/create")
    public Result create(HttpServletRequest request,
                         @RequestParam("ids[]") Integer [] ids,
                         @RequestParam("leaveAffairs[]") Double [] leaveAffairs,
                         @RequestParam("leaveSicks[]") Double [] leaveSicks,
                         @RequestParam("leaveYears[]") Double [] leaveYears,
                         @RequestParam("leaveMaternitys[]") Double [] leaveMaternitys,
                         @RequestParam("leaveMarriages[]") Double [] leaveMarriages,
                         @RequestParam("leaveFunerals[]") Double [] leaveFunerals,

                         Integer repeat,



                         HttpServletResponse response) {

        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        if(null==user){
            return  new Result(Status.NOUSER,"用户不存在!",null);
        }
        user =userMapper.selectByPrimaryKey(user.getUserId());
        Date d= new Date();
        Calendar now = Calendar.getInstance();
        int year =now.get(Calendar.YEAR);
        int month =now.get(Calendar.MONTH) + 1;

        List< Attendance> attendanceList=attendanceMapper.selectByCommunityAndYearAndMonth(user.getCommunityId(),year,month);

        if(attendanceList.size()>0&&null==repeat){
            return  new Result(Status.REPEAT,"已经存在当月考勤数据!",null);
        }
        System.out.println(user.getCommunityId());
        for (int i=0;i<ids.length;i++) {
            int id =ids[i];
            Attendance attendance =new Attendance();
            if(null!=repeat&&repeat==1){
                 attendance =attendanceMapper.selectByPersonAndYearAndMonth(id,year,month);
                 if(null==attendance){
                     return  new Result(Status.ERROR,"发生错误!",null);
                 }
                attendance.setRegisterTime(d);
                attendance.setUserId(user.getUserId());
                 attendance.setPersonName(user.getRealName());
                attendance.setLeaveAffairs(leaveAffairs[i]);
                attendance.setLeaveSick(leaveSicks[i]);
                attendance.setLeaveYear(leaveYears[i]);
                attendance.setLeaveMaternity(leaveMaternitys[i]);
                attendance.setLeaveMarriage(leaveMarriages[i]);
                attendance.setLeaveFuneral(leaveFunerals[i]);
                if(attendanceMapper.updateByPrimaryKeySelective(attendance)>0){
                    logger.info("更新成功");


                }else {
                    return  new Result(Status.ERROR,"更新失败",null);
                }


            }else{
                attendance.setPersonId(id);
                attendance.setCommunityId(user.getCommunityId());
                attendance.setDepartId(user.getDepartId());
                attendance.setUserId(user.getUserId());
                attendance.setPersonName(personMapper.selectByPrimaryKey(id).getPersonName());
                attendance.setAttYear(year);
                attendance.setAttMonth(month);


                attendance.setRegisterTime(d);
                attendance.setLeaveAffairs(leaveAffairs[i]);
                attendance.setLeaveSick(leaveSicks[i]);
                attendance.setLeaveYear(leaveYears[i]);
                attendance.setLeaveMaternity(leaveMaternitys[i]);
                attendance.setLeaveMarriage(leaveMarriages[i]);
                attendance.setLeaveFuneral(leaveFunerals[i]);

                if(attendanceMapper.insert(attendance)>0){
                    logger.info("插入成功");


                }else {
                    return  new Result(Status.ERROR,"插入失败",null);
                }



            }










        }

        List<AttendanceNotify> attendanceNotifyList =attendanceNotifyMapper.selectByCommunityAndYearAndMonth(user.getCommunityId(),year,month);
        AttendanceNotify attendanceNotify;
        if(attendanceNotifyList.size()>0){
            attendanceNotify =attendanceNotifyList.get(0);
            attendanceNotify.setFlag(2);
            attendanceNotifyMapper.updateByPrimaryKey(attendanceNotify);


        }else{

            attendanceNotify =new AttendanceNotify();
            attendanceNotify.setFlag(2);//代表已上传
            attendanceNotify.setMonth(month);
            attendanceNotify.setYear(year);
            attendanceNotify.setCommunityId(user.getCommunityId());
            attendanceNotifyMapper.insertSelective(attendanceNotify);
        }


        logger.info("批量插入成功");
        return  new Result(Status.SUCCESS,"批量插入成功",null);


    }
    private void getAttendance(HttpServletRequest request, String prefix, Attendance attendance,  List<FieldError> fieldErrorList ) {

        try {
            attendance.setLeaveAffairs(Double.valueOf(request.getParameter(prefix + "leaveAffairs]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为整形数字");
            FieldError fieldError =new FieldError("leaveAffairs","格式不正确，必须为整形数字");
            fieldErrorList.add(fieldError);
        }

        try {
            attendance.setLeaveSick(Double.valueOf(request.getParameter(prefix + "leaveSick]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为整形数字");
            FieldError fieldError =new FieldError("leaveSick","格式不正确，必须为整形数字");
            fieldErrorList.add(fieldError);
        }

        try {
            attendance.setLeaveYear(Double.valueOf(request.getParameter(prefix + "leaveYear]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为整形数字");
            FieldError fieldError =new FieldError("leaveYear","格式不正确，必须为整形数字");
            fieldErrorList.add(fieldError);
        }
        try {
            attendance.setLeaveMaternity(Double.valueOf(request.getParameter(prefix + "leaveMaternity]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为整形数字");
            FieldError fieldError =new FieldError("leaveMaternity","格式不正确，必须为整形数字");
            fieldErrorList.add(fieldError);
        }

        try {
            attendance.setLeaveMarriage(Double.valueOf(request.getParameter(prefix + "leaveMarriage]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为整形数字");
            FieldError fieldError =new FieldError("leaveMarriage","格式不正确，必须为整形数字");
            fieldErrorList.add(fieldError);
        }
        try {
            attendance.setLeaveFuneral(Double.valueOf(request.getParameter(prefix + "leaveFuneral]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为整形数字");
            FieldError fieldError =new FieldError("leaveFuneral","格式不正确，必须为整形数字");
            fieldErrorList.add(fieldError);
        }


    }


}
